import { IUserModel } from '@/models/user'
import util from '@/utils/util'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

// 登录步骤枚举
export const enum StepsEnum {
  Login,//手机号登录和密码登录
  Forgot,//忘记密码
  Reset,//重置密码
  Success//重置成功
}

// 验证码或密码选项卡枚举
export const enum TabsEnum {
  Verifycode,//验证码登录
  Password,//密码登录
}

// 忘记密码步骤
export const enum ForgotStepsEnum {
  Phone,//手机号
  Verifycode,//验证码
}
export interface IforgotFormData {
  phone?: string
  uuid?: React.Key
  verifycode?: string
  password?: string
  confirm_password?: string
}
// 为 slice state 定义一个类型
interface LoginState {
  step: number
  phone: string
  tabIndex: number
  forgotStep: number
  forgotFormData: IforgotFormData
  userInfo: IUserModel
  diskStatus: string
}

// 使用该类型定义初始 state
const initialState: LoginState = {
  step: StepsEnum.Login, //登录，忘记密码，重置密码，成功的步骤标识
  phone: localStorage.getItem("phone") || '',
  tabIndex: TabsEnum.Password,//验证码登录或者密码登录
  forgotStep: ForgotStepsEnum.Phone,//忘记密码步骤
  forgotFormData: {
    phone: '',
    uuid: '',
    verifycode: '',
  },//忘记密码步骤中的表单数据
  userInfo: util.getInitUserInfo(),//用户信息
  diskStatus: "",//磁盘异常信息
}

export const useLoginStore = createSlice({
  name: 'login',
  initialState,
  reducers: {
    updateStep: (state: LoginState, action: PayloadAction<number>) => {
      state.step = action.payload
    },
    updatePhone: (state: LoginState, action: PayloadAction<string>) => {
      state.phone = action.payload
    },
    updateTabIndex: (state: LoginState, action: PayloadAction<number>) => {
      state.tabIndex = action.payload
    },
    updateForgotStep: (state: LoginState, action: PayloadAction<number>) => {
      state.forgotStep = action.payload
    },
    updateForgotFormData: (state: LoginState, action: PayloadAction<IforgotFormData>) => {
      state.forgotFormData = { ...state.forgotFormData, ...action.payload }
    },
    updateUserInfo: (state: LoginState, action: PayloadAction<IUserModel>) => {
      state.userInfo = action.payload
    },
    updateDiskStatus: (state: LoginState, action: PayloadAction<string>) => {
      state.diskStatus = action.payload
    },
  }
})


// Action creators are generated for each case reducer function
export const { updateStep, updatePhone, updateTabIndex, updateForgotStep, updateForgotFormData, updateUserInfo, updateDiskStatus } = useLoginStore.actions
export default useLoginStore.reducer